package aiowang.activemq.java;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

/**
 * @author aiowang
 * @description:
 * @date 2021/8/11 23:10
 */
public class Receiver {

    /**消息服务器的连接地址**/
    public static final String BROKER_URL = "tcp://quanguo119.telewave.com.cn:61616";

    public static void main(String[] args) {
        Receiver receiver = new Receiver();
        receiver.receiveMessage();
    }

    /**
     * 接收消息
     *
     */
    public void receiveMessage () {

        Connection connection = null;
        Session session = null;
        MessageConsumer messageConsumer = null;

        try {
            //1.创建一个连接工厂
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(BROKER_URL);

            //2.创建一个连接
            connection = connectionFactory.createConnection();

            //3.创建一个Session
            session = connection.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);

            //4.创建一个目的地
            Destination destination = session.createQueue("alarmInfoQueen.510100");

            //5.创建一个消息的消费者（接收者）
            messageConsumer = session.createConsumer(destination);

            //接收消息之前，需要把连接启动一下
            //connection.start();

            messageConsumer.setMessageListener((message)->{
                String text = null;
                try {
                    text = ((TextMessage) message).getText();
                } catch (JMSException e) {
                    e.printStackTrace();
                }
                System.out.println("接收到的消息内容是：" + text);
            });


            //6.接收消息
//            Message message = messageConsumer.receive();
//
//            //判断消息的类型
//            if (message instanceof TextMessage) {
//                //判断是否是文本消息
//                String text = ((TextMessage) message).getText();
//                System.out.println("接收到的消息内容是：" + text);
//            }
        } catch (JMSException e) {
            e.printStackTrace();
        }
//        } finally {
//            try {
//                //关闭连接释放资源
//                if (null != messageConsumer) {
//                    messageConsumer.close();
//                }
//                if (null != session) {
//                    session.close();
//                }
//                if (null != connection) {
//                    connection.close();
//                }
//            } catch (JMSException e) {
//                e.printStackTrace();
//            }
//        }
    }
}
